﻿using System.Collections.Generic;
using PEProtocol;

/**
 * 体力恢复系统
 */
public class PowerSys{
    private static PowerSys instance = null;

    public static PowerSys Instance{
        get{
            if (instance == null){
                instance = new PowerSys();
            }

            return instance;
        }
    }

    private CacheSvc cacheSvc = null;

    public void Init(){
        cacheSvc = CacheSvc.Instance;
        TimerSvc.Instance.AddTimerTask(CalcPowerAdd, PECommon.PowerAddSpace, PETimeUnit.Minute, -1);
        PECommon.Log("PowerSys Init done");
    }

    private void CalcPowerAdd(int tid){
        //计算体力增长
        PECommon.Log("All Online Player Calc Power Incress...");
        GameMsg msg = new GameMsg{
            cmd = (int)CMD.PshPower
        };
        msg.pshPower = new PshPower();
        
        //所有在线玩家获得实时的体力增长
        Dictionary<ServerSession,PlayerData> onlineCache = cacheSvc.GetOnlineCache();
        foreach (var item in onlineCache){
            PlayerData pd = item.Value;
            ServerSession session = item.Key;
            int powerMax = PECommon.GetPowerLimit(pd.level);
            if (pd.power >= powerMax){
                continue;
            }
            else{
                pd.power += PECommon.PowerAddCount;
                pd.time = TimerSvc.Instance.GetNowTime();
                if (pd.power > powerMax){
                    pd.power = powerMax;
                }

                if (!cacheSvc.UpdatePlayerData(pd.id, pd)){
                    msg.err = (int)ErrorCode.UpdateDBError;
                }
                else{
                    msg.pshPower.power = pd.power;
                    session.SendMsg(msg);
                }
            }
        }
    }
}
